package lyq.spec.edu.practical;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
  * @author RB
  * @date 2018/1/18 10:29
  */
public class FirstFragment extends Fragment implements MyListViewUtils.LoadListener{

    private MyListViewUtils listViewUtils;

    private List<Message> messageList = new ArrayList<Message>();

    private ArrayAdapter<Message> adapter;

    String URL = "http://www.yyjsx.xyz/api/message/list?category=NEWS&start=";

    int a = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //创建界面FirstFragment
        View view= inflater.inflate(R.layout.fragment_first , container, false);
        //界面初始化
        sendRequestWihtOkhttp();
        listViewUtils = (MyListViewUtils)view.findViewById(R.id.news_list);
        adapter = new MessageAdapter(getContext(), R.layout.list_view, messageList);
        listViewUtils.setAdapter(adapter);

        return view;
    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        LayoutInflater inflater=LayoutInflater.from(getContext());
        Init();
        listViewUtils.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Message message = messageList.get(position-1);
                //position 点击的Item位置，从0开始算
                Intent intent=new Intent(getActivity(),ActivityObtained.class);
                intent.putExtra("Message",message.getContent());//传递给下一个Activity的值
                startActivity(intent);//启动Activity
            }
        });
    }
    @Nullable
    /**
     * 发起网络请求
     */
    private void sendRequestWihtOkhttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 构造客户端，相当于浏览器
                    OkHttpClient client = new OkHttpClient();
                    // 构造请求，相当于在浏览器里输入地址
                    Request request = new Request
                            .Builder()
                            .url(URL+a)
                            .build();
                    // 发送请求，相当于在浏览器按回车
                    Response response = client.newCall(request).execute();
                    // 更新ListView
                    String body = response.body().string();
                    parseJson(body);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void parseJson(String jsonStr){
        try {
            JSONObject jobj = new JSONObject(jsonStr);
            String dataStr = jobj.getString("data");
            Gson gson = new Gson();
            messageList = gson.fromJson(dataStr, new TypeToken<List<Message>>(){}.getType());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void Init() {

        listViewUtils = (MyListViewUtils)getActivity().findViewById(R.id.news_list);
        listViewUtils.setInteface(this);
    }
    @Override
    public void onLoad() {
        // 设置延时三秒获取时局，用于显示加载效果
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 这里处理请求返回的结果（这里使用模拟数据）
                // 更新数据
                adapter.notifyDataSetChanged();
                // 加载完毕
                listViewUtils.loadComplete();
            }

        }, 3000);
    }

    @Override
    public void PullLoad() {
        // 设置延时三秒获取时局，用于显示加载效果
        new Handler().postDelayed(new Runnable() {
            @Override

            public void run() {
                // 这里处理请求返回的结果（这里使用模拟数据）
                a +=5;
                sendRequestWihtOkhttp();
                //wechatList.add("这是上拉刷新添加的数据");
                // 更新数据
                adapter.notifyDataSetChanged();
                // 加载完毕
                listViewUtils.loadComplete();

            }

        }, 3000);
    }
}
